package org.freespace.sch;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.freespace.model.Job;
import org.freespace.model.JobMachine;
import org.freespace.model.JobMachineCallback;
import org.freespace.service.IJobMachineCallbackService;
import org.freespace.service.IJobMachineService;
import org.freespace.service.IJobService;
import org.freespace.service.IMachineService;
import org.freespace.utils.SpringBeanUtil;
import org.freespace.utils.enums.JobStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Configuration
@EnableScheduling
public class SchJob {

//    @Scheduled(cron = "*/3 * * * * ?")
    public void finishJob() {
        IMachineService machineService = (IMachineService) SpringBeanUtil.getBean("machineService");
        IJobService jobService = (IJobService) SpringBeanUtil.getBean("jobService");
        IJobMachineService jobMachineService = (IJobMachineService) SpringBeanUtil.getBean("jobMachineService");
        IJobMachineCallbackService jobMachineCallbackService = (IJobMachineCallbackService) SpringBeanUtil.getBean("jobMachineCallbackService");

        List<Job> doingJobs = jobService.list(Wrappers.<Job>lambdaQuery().eq(Job::getStatus, JobStatus.DOING.getType()));

        for (Job doingJob : doingJobs) {
            List<String> jobIps = jobMachineService.list(Wrappers.<JobMachine>lambdaQuery().eq(JobMachine::getJobId, doingJob.getId())).parallelStream().map(m -> machineService.getById(m.getMachineId()).getIp()).collect(Collectors.toList());
            List<JobMachineCallback> finishJobIps = jobMachineCallbackService.list(Wrappers.<JobMachineCallback>lambdaQuery().eq(JobMachineCallback::getJobId, doingJob.getId()));
            List<String> finishIps = finishJobIps.parallelStream().map(m -> m.getIp()).collect(Collectors.toList());
            LocalDateTime maxEndTime = finishJobIps.parallelStream().map(m -> m.getEndTime()).max(Comparator.comparing(i -> i)).get();
            if (finishIps.size() == jobIps.size()) {
                //更新作业状态为完成
                doingJob.setEndTime(maxEndTime);
                doingJob.setStatus(JobStatus.FINISHED.getType());
                jobService.updateById(doingJob);
                //注销监控

                //翻转压测机器状态

                //删除插件

                //重启
            }

        }
    }
}
